layui.use(['form', 'layer'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery;


    var MapBaidu = function () {


        // var mapObj = '#map_container';
        // var addressObj = '#detailed_address';


        return {
            initMap: function (lng, lat) {
                //创建Map实例
                var map = new BMap.Map('map_container');
                // 初始化坐标
                var point = new BMap.Point(lng, lat);
                var offsetY = 200;
                // 地图平移缩放控件：默认左上方
                map.addControl(new BMap.NavigationControl());
                // 比例尺控件，默认位于地图左下方，显示地图的比例关系
                map.addControl(new BMap.ScaleControl());
                map.centerAndZoom(point, 12);
                // 添加鼠标滚动缩放
                map.enableScrollWheelZoom(true);
                // 显示地址信息窗口
                var marker = new BMap.Marker(point);
                // 把标注添加到地图上
                map.addOverlay(marker);

                // 地址解析类
                var geo = new BMap.Geocoder();


                var _search = {
                    _address: $('#detailed_address'),
                    unChecked: function (val) {
                        return (val == '' || typeof (val) == 'undefined' || val == null || val == 0) ? false : true;
                    },
                    keyword: function () {
                        var keywords = '';
                        if (this.unChecked(this._address.val())) {
                            var province = $('#province').val();
                            if (province && province != 0) {
                                keywords += $('#province').find('option:selected').text();
                            }
                            var city = $('#city').val();
                            if (city && city != 0) {
                                keywords += $('#city').find('option:selected').text();
                            }
                            var district = $('#district').val();
                            if (district && district != 0) {
                                keywords += $('#district').find('option:selected').text();
                            }

                            keywords += this._address.val();
                            console.log(keywords);
                        }

                        return keywords;
                    },
                    // 删除标注
                    deletePoint: function () {
                        var allOverlay = map.getOverlays();
                        for (var i = 0; i < allOverlay.length; i++) {
                            map.removeOverlay(allOverlay[i]);
                        }
                    },
                    init: function () {
                        // 绑定百度地图
                        // 定义local
                        var local = new BMap.LocalSearch(map, {
                            renderOptions: {
                                map: map,
                                panel: 'results', // 结果容器id
                                autoViewport: true, // 自动结果标注
                                selectFirstResult: true, // 指定到第一个目标
                                enableRouteSearchBox: true,
                                enableRouteInfo: true
                            },
                            pageCapacity: 1
                        });

                        local.setSearchCompleteCallback(function (searchResult) {
                            if (searchResult) {
                                var poi = searchResult.getPoi(0);
                                if (poi) {
                                    map.centerAndZoom(poi.point, 12);
                                    geo.getLocation(poi.point, function (res) {
                                        //var addComp = res.addressComponents;
                                        $('.longitude').val(poi.point.lng);
                                        $('.latitude').val(poi.point.lat);
                                        console.log('经纬度：' + poi.point.lat + ' ' + poi.point.lng);
                                    });
                                }
                            }
                        });
                        local.search(this.keyword());
                    },
                };

                // 全局变量：存储address字符串长度做判断
                var _thisLength = '';
                $('#detailed_address').keydown(function () {
                    _thisLength = $(this).val().length;
                });

                $('#detailed_address').keyup(function () {
                    var _newLength = $(this).val().length;
                    var timer = setTimeout(function () {
                        if (_thisLength <= _newLength) {
                            _search.deletePoint();
                            _search.init();
                        } else {
                            clearTimeout(timer);
                        }
                    }, 1000);
                });
                $('#detailed_address').blur(function () {
                    _search.deletePoint();
                    _search.init();
                });

                // 初始化
                if ($('#detailed_address').val() != '') {
                    $('#detailed_address').blur();
                }
            },

            // 初始化当前城市
            initLocalCity: function () {
                var _this = this;

                var myCity = new BMap.LocalCity();
                myCity.get(function (result) {
                    //console.log(result);
                    //var point = result.center;
                    var lng = result.center.lng;
                    var lat = result.center.lat;

                    _this.initMap(lng, lat)
                });
            },

            // 初始化当前位置
            initLocalPoint: function () {
                var _this = this;

                if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition(function (position) {
                        var lng = position.coords.longitude;
                        var lat = position.coords.latitude;
                        //console.log(lng+':'+lat);
                        var gpsPoint = new BMap.Point(lng, lat);

                        // 坐标转成百度需要的坐标，并初始化地图
                        // gpsPoint：转换前坐标，第二个参数为转换方法，0表示gps坐标转换成百度坐标，callback回调函数，参数为新坐标点
                        BMap.Convertor.translate(gpsPoint, 0, function (data) {
                            _this.initMap(data.lng, data.lat);
                        })
                    })
                } else {
                    console.log('Your browser does not support Geolocation!');
                }
            },

            init: function () {
                if ($('#map_container').length > 0) {
                    //this.initMap(116.404, 39.915); // 一般初始化地图，设置北京天安门
                    this.initLocalCity();
                    //this.initLocalPoint();
                }
            }
        };
    }();


    $(function () {
        MapBaidu.init();
    });
});
